package com.evildog.workspace.security.jwt.util;


import com.evildog.workspace.common.exception.UnAuthException;
import com.evildog.workspace.common.util.RequestUtil;
import com.evildog.workspace.common.util.SpringContextHolder;
import com.evildog.workspace.common.util.WsAssert;
import com.evildog.workspace.security.jwt.constant.TokenConstant;
import com.evildog.workspace.security.jwt.core.TokenUserInfo;
import com.evildog.workspace.security.jwt.enums.SecurityJwtCustomExceptionDesc;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.util.StringUtils;

/**
 * 安全认证相关util
 */
@Slf4j
public class SecurityUtil {


    /**
     * 获取用户信息
     * (servlet 模式)
     *
     * @return TokenUserInfo
     */
    public static TokenUserInfo getUser() {
        String userInfoJson = RequestUtil.getHeader(TokenConstant.USER_INFO_HEADER);

        if(!StringUtils.hasText(userInfoJson)){
            return null;
        }

        ObjectMapper bean = SpringContextHolder.getBean(ObjectMapper.class);
        TokenUserInfo tokenUserInfo;
        try {
            tokenUserInfo = bean.readValue(userInfoJson, TokenUserInfo.class);
        } catch (JsonProcessingException e) {
            log.error("getUser error,", e);
            throw new UnAuthException(SecurityJwtCustomExceptionDesc.JWT_PARSE_ERROR);
        }
        return tokenUserInfo;
    }

    /**
     * 获取用户 userId
     *
     * @return userId
     */
    public static Long getUserId() {
        TokenUserInfo user = getUser();

        if(user == null){
            return null;
        }

        return user.getUserId();
    }


    /**
     * 获取用户信息
     *
     * @param claims claims
     * @return TokenUserInfo
     */
    public static TokenUserInfo getUser(Claims claims) {
        WsAssert.notNull(claims, SecurityJwtCustomExceptionDesc.CLAIM_REQUIRED);

        Long userId = NumberUtils.toLong(String.valueOf(claims.get(TokenConstant.USER_ID)));
        String avatar = String.valueOf(claims.get(TokenConstant.AVATAR));
        String nickname = String.valueOf(claims.get(TokenConstant.NICKNAME));

        return new TokenUserInfo()
                .setUserId(userId)
                .setAvatar(avatar)
                .setNickname(nickname)
                ;
    }


}
